package net.cyue.simple.container;

import net.cyue.simple.container.data.InjectableMetaType;
import net.cyue.simple.container.data.InstanceWrapper;
import net.cyue.simple.container.data.MetaType;
import net.cyue.simple.container.injector.AbstractInstanceRegistry;
import net.cyue.simple.container.injector.DefaultInstanceRegistry;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class InstanceContainer {
    private static final AbstractInstanceRegistry INSTANCE_REGISTRY = new DefaultInstanceRegistry();
    private final Map<MetaType, InstanceWrapper> injectableMap = new ConcurrentHashMap<>();

    public AbstractInstanceRegistry getInstanceRegistry() {
        return INSTANCE_REGISTRY;
    }

    public Object getInjectableInstance(MetaType type) {
        InstanceWrapper wrapper = this.injectableMap.get(type);
        if (wrapper == null) {
            return null;
        }
        return wrapper.getInstance();
    }
    public Object[] getInjectableInstances() {
        InstanceWrapper[] wrapperArray = this.injectableMap.values().toArray(new InstanceWrapper[0]);
        Object[] instanceArray = new Object[wrapperArray.length];
        for (int i = 0; i < instanceArray.length; i++) {
            instanceArray[i] = wrapperArray[i].getInstance();
        }
        return instanceArray;
    }
    public InstanceWrapper[] getInjectableInstanceWrappers(MetaType type) {
        return this.injectableMap.values().toArray(new InstanceWrapper[0]);
    }

    public void addInjectable(InjectableMetaType injectableMetaType) {
        InstanceWrapper wrapper = this.injectableMap.get(injectableMetaType);
        if (wrapper == null) {
            wrapper = INSTANCE_REGISTRY.registerInstance(injectableMetaType);
            this.injectableMap.put(injectableMetaType, wrapper);
        }
    }
}
